package manage

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/constants"
	"gozero-demo/internal/repo/mysql"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
	"gozero-demo/internal/utils"
)

type OrdersListLogic struct {
	logx.Logger
	ctx        context.Context
	svcCtx     *svc.ServiceContext
	ordersRepo *mysql.OrdersRepo
	userRepo   *mysql.UserRepo
	goodsRepo  *mysql.GoodsRepo
}

// 订单列表
func NewOrdersListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrdersListLogic {
	return &OrdersListLogic{
		Logger:     logx.WithContext(ctx),
		ctx:        ctx,
		svcCtx:     svcCtx,
		ordersRepo: mysql.NewOrdersRepo(ctx, svcCtx),
		userRepo:   mysql.NewUserRepo(ctx, svcCtx),
		goodsRepo:  mysql.NewGoodsRepo(ctx, svcCtx),
	}
}

func (l *OrdersListLogic) OrdersList(req *types.OrdersListRequest) (resp *types.CommonResponse, err error) {
	count, modelsDataList, err := l.OrdersListData(req)
	if err != nil {
		return types.ErrorResponse(constants.CodeServerError.Code, err.Error(), l.ctx), err
	}
	modelsListData := types.OrdersListData{
		CommonPageListResp: types.CommonPageListResp{
			Page:     req.Page,
			PageSize: req.PageSize,
			Total:    count,
		},
		List: modelsDataList,
	}
	return types.SuccessResponse(modelsListData, l.ctx), nil
}

func (l *OrdersListLogic) OrdersListData(req *types.OrdersListRequest) (respCount int64, respList []types.OrdersData, err error) {
	//基础查询条件:查询相等
	conds := make(map[string]interface{})
	if req.UserID > 0 {
		conds["user_id"] = req.UserID
	}
	if req.GoodsNo != "" {
		conds["goods_no"] = req.GoodsNo
	}
	if req.ID > 0 {
		conds["id"] = req.ID
	}

	//更多查询条件
	condsMore := make(map[string]interface{})
	if req.GoodsNameSnapshot != "" {
		condsMore["goods_name_snapshot"] = req.GoodsNameSnapshot
	}
	if req.CreateTimeStart != "" {
		condsMore["create_time_start"] = req.CreateTimeStart
	}
	if req.CreateTimeEnd != "" {
		condsMore["create_time_end"] = req.CreateTimeEnd
	}

	list, count, err := l.ordersRepo.GetOrdersListByConditions(conds, condsMore, int(req.Page), int(req.PageSize))
	if err != nil {
		return 0, nil, err
	}

	//提取list中的关联数据
	var goodsNos []string
	var userIds []int64
	for _, v := range list {
		goodsNos = append(goodsNos, utils.CommaSeparatedStringToStringSlice(v.GoodsNo)...)
		userIds = append(userIds, v.UserID)
	}
	//根据多个user_id获取用户名称
	userMap, err := l.userRepo.GetUserNameMapByIds(utils.RemoveDuplicatesInt64Slice(userIds))
	if err != nil {
		logx.WithContext(l.ctx).Errorf("get user name map failed: %v", err)
	}

	//循环处理list
	var modelsDataList []types.OrdersData
	for _, v := range list {
		modelsDataItem := types.OrdersData{
			OrdersEditRequest: types.OrdersEditRequest{
				ID:                v.ID,
				GoodsNo:           v.GoodsNo,
				GoodsNameSnapshot: v.GoodsNameSnapshot,
				Receiver:          v.Receiver,
				ContactPhone:      v.ContactPhone,
				Address:           v.Address,
				PayPrice:          float64(v.PayPrice / 100),
			},
			OrderNo:    v.OrderNo,
			UserID:     v.UserID,
			UserName:   userMap[v.UserID],
			Status:     v.Status,
			CreateTime: v.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime: v.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		if v.PayTime == nil {
			modelsDataItem.PayTime = ""
		} else {
			modelsDataItem.PayTime = v.PayTime.Format("2006-01-02 15:04:05")
		}
		//组装最后的结构体
		modelsDataList = append(modelsDataList, modelsDataItem)
	}

	return count, modelsDataList, nil
}
